/*
 * @作者: Fultom
 * @创建时间: 2021-10-20 16:09:24
 * @最近修改时间: 2025-07-10 10:53:39
 * @功能: 接口请求工具类
 */

import { AppToast } from '@/utils/publicMethod'
import request from '@/utils/request'
import upload from '@/utils/upload'
import { PermissionHelp, PermissionScope } from '@/utils/apiMethod'
import login from './api/login'

interface ServeReqNetWorkingDataOption {
  url: string
  method?: 'GET' | 'POST'
  params?: any
  contentType?: 'json' | 'form'
}

/** get post 接口数据请求 */
export const ServeReqNetWorkingData = (option: ServeReqNetWorkingDataOption): Promise<any> => {
  return request({
    url: option.url,
    data: option.params,
    method: option.method,
    contentType: option.contentType,
  })
}

/**
 *
 * 图片选取并上传 1 张
 * @param option
 * url:上传的链接
 * sourceType:选择数据来源 album 从相册选图，camera 使用相机
 * params:额外参数
 * count:数量 不传默认1
 * @returns Promise
 */
export const ServeUploadImageNetWorkingData = (option: {
  url: string
  sourceType?: ('album' | 'camera')[]
  params?: any
  count?: number
}): Promise<any> => {
  return new Promise((resolve, reject) => {
    const imgsList = [] as string[]
    PermissionHelp(PermissionScope.camera, () => {
      uni.chooseImage({
        count: option.count ? option.count : 1,
        success: (res) => {
          const tempFilePaths = res.tempFilePaths as any //图片的本地文件路径列表;
          const promiseList = [] as any[]
          tempFilePaths.forEach((item: string) => {
            promiseList.push(
              new Promise((resolve, reject) => {
                upload({
                  url: option.url,
                  filePath: item,
                  fileType: 'image',
                  formData: option.params,
                  name: 'file',
                }).then((res) => {
                  resolve(res)
                })
              }),
            )
          })
          Promise.all(promiseList).then((res) => {
            res.forEach((item) => {
              imgsList.push(item.data[0])
            })
            resolve(imgsList)
          })
        },
        fail: (res) => {
          AppToast('获取图片失败')
          reject('获取图片失败')
        },
      })
    })
  })
}

/** 登录 */
export const API_LOGIN = login
